var orderMoney;
var receivableMoney;
var isEditing=false;//是否处于编辑状态
var money;//还没回款金额
$(function() {
	orderMoney=$("input[name='orderMoney']").val();
	receivableMoney=$("input[name='receivableMoney']").val();
	money=parseFloat(orderMoney)-parseFloat(parseInt(receivableMoney));//计算出还没回款的金额
	$('#receivable-window').window('open').window('center').window('setTitle',
			'回款计划');
	$("#receivable-add-detail-dg").datagrid({
		fitColumns : true,
		singleSelect : true,
		fit : true,
		columns : [ [
			{field:'installment',width:40,title:'期数',formatter:function(value,row,index){
				var ary0=["一", "二", "三", "四", "五", "六", "七", "八", "九"];
				return "第"+ary0[index]+"期";
			}},
			{field:"planTime" ,width:80,title:'计划回款时间',
				editor:{ type:'datebox',options:{required:true, },
			}},
			{field:"planMoney", width:80,title:'计划回款金额',
				editor:{type:'numberbox',options:{precision:1,required:true,}}},
			{field:"state" ,width:50 ,align:"center",title:'回款状态',formatter:function(){
				return '未回款';
			}},
			{field:'note',width:100,editor:'text',title:'备注'},
			{field:'op',width:50,title:'操作',
				formatter:function(value,row,index){
					if (isEditing){
						var s = '<a title="保存" href="javascript:void(0)" onclick="saverow(this)"><i class="iconfont icon-queding"></i></a> ';
						var c = '<a title="取消" href="javascript:void(0)" onclick="cancelrow(this)"><i class="iconfont icon-cuowuguanbiquxiao-yuankuang"></i></a>';
						return s+c;
					} else {
						var e = '<a title="编辑" href="javascript:void(0)" onclick="editrow(this)"><i class="iconfont icon-bianji"></i></a> ';
						var d = '<a title="删除" href="javascript:void(0)" onclick="deleterow(this)"><i class="iconfont icon-msnui-trash"></i></a>';
						return e+d;
					}
				}
			},
		]],
		onEndEdit:function(index,row){
			
		},
		onBeforeEdit:function(index,row){
			isEditing = true;
			$("#receivable-add-detail-dg").datagrid('refreshRow', index);
		},
		onAfterEdit:function(index,row){
			isEditing = false;
			$("#receivable-add-detail-dg").datagrid('refreshRow', index);
		},
		onCancelEdit:function(index,row){
			isEditing = false;
			$("#receivable-add-detail-dg").datagrid('refreshRow', index);
		}
	});
})
// 编辑
function getRowIndex(target) {
	var tr = $(target).closest('tr.datagrid-row');
	return parseInt(tr.attr('datagrid-row-index'));
}
function editrow(target) {
	$('#receivable-add-detail-dg').datagrid('beginEdit', getRowIndex(target));
}
function deleterow(target) {
	$.messager.confirm('提示', '确定要删除吗?', function(r) {
		if (r) {
			$('#receivable-add-detail-dg').datagrid('deleteRow', getRowIndex(target));
		}
	});
}
function saverow(target) {
	var index=getRowIndex(target);
	var rows = $('#receivable-add-detail-dg').datagrid('getRows');// 获取当前的数据行
	var edm=$('#receivable-add-detail-dg').datagrid('getEditor', {index:index,field:'planMoney'});
	var edt=$('#receivable-add-detail-dg').datagrid('getEditor', {index:index,field:'planTime'});
	var planMoney = $(edm.target).numberbox('getValue');
	var planTime = $(edt.target).datebox('getValue');
	console.log(getMoney());
	if (planTime<nowtime()) {
		isEditing = true;
		$.messager.alert("提示","计划回款时间不能小于当前时间！");
	}else if(planMoney>getMoney()){
		isEditing = true;
		$.messager.alert("提示","添加失败了！没有这么多要回款的金额！");
	}else{
		if(rows.length>1){
			//获取上一个回款计划的时间
			var planTime1=rows[rows.length-2].planTime;
			console.log(planTime1);
			console.log(planTime);
			if (planTime<planTime1) {
				isEditing = true;
				$.messager.alert("提示","计划回款时间不能小于上一个计划回款时间","error");
			}else{
				$('#receivable-add-detail-dg').datagrid('endEdit', getRowIndex(target));
			}
		}else{
			$('#receivable-add-detail-dg').datagrid('endEdit', getRowIndex(target));
		}
	}
}
function cancelrow(target) {
	$('#receivable-add-detail-dg').datagrid('cancelEdit', getRowIndex(target));
}
// 删除一行回款计划
function destroyReceivable() {
	var row = $('#receivable-add-detail-dg').datagrid('getSelected');
	if (row) {
		var rowIndex = $('#receivable-add-detail-dg').datagrid('getRowIndex',
				row);
		$.messager.confirm('提示', '确定要删除吗?', function(r) {
			if (r) {
				$('#receivable-add-detail-dg').datagrid('deleteRow', rowIndex);
			}
		});
	}
	$("#receivable-add-detail-dg").datagrid('refresh');  
}
//新增一行
function newReceivable(){
	if(getMoney()>0){
		$('#receivable-add-detail-dg').datagrid('appendRow', {
			
		});
		var rows = $('#receivable-add-detail-dg').datagrid('getRows');// 获取当前的数据行
		$("#receivable-add-detail-dg").datagrid('beginEdit',rows.length-1);
	}else{
		$.messager.alert("提示","不能再添加了，计划回款金额已经达到上限！","error");
	}
}
//获取当前已经回款的金额
function getMoney(){
	
	var money1=0;
	var rows = $('#receivable-add-detail-dg').datagrid('getRows')// 获取当前的数据行
	console.log(rows);
	for (var i = 0; i < rows.length; i++) {
		console.log(rows[i]['planMoney']);
	}
	console.log(parseFloat(money));
	console.log(parseFloat(money1));
	return parseFloat(money)-parseFloat(money1);
}
//保存
function saveReceivable(){
	var orderMoney1=$("input[name='orderMoney']").val();
	var receivableMoney1=$("input[name='receivableMoney']").val();
	var money1=parseFloat(orderMoney)-parseFloat(parseInt(receivableMoney));//计算出还没回款的金额
	var orderid = $("input[name='orderid']").val();
	var rows = $('#receivable-add-detail-dg').datagrid('getRows')// 获取当前的数据行
	if (rows.length < 1) {// 如果没有产品
		$.messager.confirm('提示', '还没有添加任何回款计划，要继续吗?', function(r) {
			if (r) {
				$.messager .confirm( '提示', '是否要建立回款明细？', function(r) {
					if (r) {
						window.location.href = 'http://localhost:8080/crm/crm/order/addReceivable/'
								+ orderid;
					}		
				});
			}
		});
	} else {
		var money2=0;//统计回款金额
		var param = new Array();
		for (var i = 0; i < rows.length; i++) {
			money2+=parseFloat(rows[i]['planMoney']);
			var object = new Object();
			object.installment = rows[i]['installment'];
			object.planTime = rows[i]['planTime'];
			object.planMoney = rows[i]['planMoney'];
			object.state = rows[i]['state'];
			object.note = rows[i]['note'];
			param.push(object);
		}
		if(money1!=money2){
			$.messager.alert("提示","保存失败！还有未回款的金额哟！");
		}else{
			$ .ajax({
				type : "POST",
				url : "crm/receivable/savelist/" + orderid,
				data : {
					"param" : JSON.stringify(param),
				},
				dataType : "json",
				traditional : true,
				contentType : "application/x-www-form-urlencoded; charset=utf-8",
				async : false,
				success : function(data) {
						$.messager.alert( '消息', '保存回款计划成功！',"info");
						window.top.opener = null; 
						window.close();
				},
				error : function() {
					$.messager .alert( '消息', '保存回款计划失败！',"info");
				}		
			});
		}
	}
}
//获取当前日期yyyy-MM-dd
function nowtime(){//将当前时间转换成yyyymmdd格式
    var mydate = new Date();
    var str = "" + mydate.getFullYear();
    var mm = mydate.getMonth()+1
    if(mydate.getMonth()>9){
     str +="-" +mm;
    }
    else{
     str += "-0" + mm;
    }
    if(mydate.getDate()>9){
     str += "-"+mydate.getDate();
    }
    else{
     str += "-0" + mydate.getDate();
    }
    return str;
  }